package com.corn.zk.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.KeeperException;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/12 17:34
 */
@Slf4j
public class CuratorLockTest {

    public static void main(String[] args) throws InterruptedException {
        // 客户端链接
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("node1:2181")
                .connectionTimeoutMs(2000)
                .sessionTimeoutMs(2000)
                .retryPolicy(new RetryNTimes(3, 500))
                .build();
        // 调用start开始连接
        client.start();
        // 阻塞到连接成功
        client.blockUntilConnected(5, TimeUnit.SECONDS);
        InterProcessLock lock1 = new InterProcessMutex(client, "/locks");
        InterProcessLock lock2 = new InterProcessMutex(client, "/locks");

        new Thread(() -> {
            log.info("线程名称:{} 开始加锁", Thread.currentThread().getName());
            try {
                lock1.acquire();
                log.info("线程名称:{} 获取到锁开始直接业务", Thread.currentThread().getName());
                Thread.sleep(10 * 1000);
                lock1.release();
                log.info("线程名称:{} 解锁", Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();


        new Thread(() -> {
            log.info("线程名称:{} 开始加锁", Thread.currentThread().getName());
            try {
                lock2.acquire();
                log.info("线程名称:{} 获取到锁开始直接业务", Thread.currentThread().getName());
                Thread.sleep(3 * 1000);
                lock2.release();
                log.info("线程名称:{} 解锁", Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
